﻿using IRepository;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Repository
{
    public class BaseRespository<T> :IBaseRespository<T> where T : class
    {
        private readonly MyContext db;

        public MyContext MyContexts { get ; set ; }

        public BaseRespository(MyContext db)
        {
            this.db = db;
            this.MyContexts = db;
        }
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(T t)
        {
            await db.Set<T>().AddAsync(t);
            return await db.SaveChangesAsync();
        }
        //别几把学了HOME知道了吗
        //知道了
        /// <summary>
        /// 增加多条
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public async Task<int> AddRangAsync(List<T> list)
        {
            await db.Set<T>().AddRangeAsync(list);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetList()
        {
            return db.Set<T>().AsQueryable();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(T t)
        {
            db.Set<T>().Update(t);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 修改多条
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public async Task<int> UpdateRangeAsync(List<T> list)
        {
            db.Set<T>().UpdateRange(list);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 根据id获取数据
        /// </summary>
        /// <param name="id">实体id</param>
        /// <returns>实体</returns>
        public async Task<T> GetItemById(int id)
        {
            return await db.Set<T>().FindAsync(id);
        }



        /// <summary>
        /// 指定条件查询
        /// </summary>
        /// <param name="exp">委托表达式(调用时需传递lamdba表达式)</param>
        /// <returns>返回满足条件的数据</returns>
        public IQueryable<T> GetList(Expression<Func<T, bool>> exp)
        {
            return db.Set<T>().Where(exp).AsQueryable();
        }


        /// <summary>
        /// 根据条件获取实体
        /// </summary>
        /// <param name="exp">委托表达式(调用时需传递lamdba表达式)</param>
        /// <returns>返回满足条件的实体</returns>
        public async Task<T> GetItemById(Expression<Func<T, bool>> exp)
        {
            return await db.Set<T>().Where(exp).FirstOrDefaultAsync();

        }
    }
}
